package com.study.spring.tcp;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;

/**
 * TCP客户端
 *
 * @author zhang
 * @version 1.0
 * @date 2019/04/03
 */
public class MsgClient {

    private static final Logger LOG = LoggerFactory.getLogger(MsgClient.class);
    private static int i = 0;
    private DataOutputStream dos = null;
    private DataInputStream dis = null;

    public static void main(String[] args) throws IOException, InterruptedException {
        MsgClient client = new MsgClient();
        client.connect("127.0.0.1", 9090);
    }

    private void sendMsg(DataOutputStream dos, String msg) throws IOException {
        byte[] bytes = msg.getBytes(StandardCharsets.UTF_8);
        int total = bytes.length + 5;
        dos.writeByte(1);
        dos.writeInt(total);
        dos.write(bytes);
        dos.flush();
    }

    public void connect(String ip, int port) throws IOException, InterruptedException {
        Socket client = new Socket(ip, port);
        InputStream is = client.getInputStream();
        OutputStream outputStream = client.getOutputStream();
        dis = new DataInputStream(is);
        dos = new DataOutputStream(outputStream);
        new Thread(() -> {
            for (; ; ) {

                try {
                    sendMsg(dos, "我爱你张毅" + ++i);
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        new Thread(() -> {
            for (; ; ) {

                try {
                    LOG.info(dis.readUTF());
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();


    }
}
